package git_cmd

import (
	"context"
	"os/exec"
	"strings"
	"time"

	"atomgit.com/openlinksaas/gitwrap/utils"
	"github.com/spf13/cobra"
)

type StatusItem struct {
	Path          string `json:"path"`
	IndexChange   bool   `json:"indexChange"`
	IndexDelete   bool   `json:"indexDelete"`
	WorkDirChange bool   `json:"workDirChange"`
	WorkDirDelete bool   `json:"workDirDelete"`
}

var _StatusCmd = &cobra.Command{
	Use: "status",
	Run: func(cmd *cobra.Command, args []string) {
		ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
		defer cancel()

		cmdPath, err := exec.LookPath("git")
		if err != nil {
			utils.OutputError(err)
			return
		}
		gitCmd := exec.CommandContext(ctx, cmdPath, "status", "-s", "--no-renames")
		gitCmd.Dir = gitFlagLocalPath
		resData, err := gitCmd.Output()
		if err != nil {
			utils.OutputError(err)
			return
		}
		itemList := []*StatusItem{}
		for _, line := range strings.Split(string(resData), "\n") {
			line = strings.TrimRight(line, "\r\n\t ")
			if len(line) < 3 {
				continue
			}
			if line[0] == byte('!') || line[1] == byte('!') {
				continue
			}
			item := &StatusItem{}
			if line[0] != byte(' ') {
				item.IndexChange = true
			}
			if line[0] == byte('D') {
				item.IndexDelete = true
			}
			if line[1] != byte(' ') {
				item.WorkDirChange = true
			}
			if line[1] == byte('D') {
				item.WorkDirDelete = true
			}
			item.Path = line[3:]
			itemList = append(itemList, item)
		}
		utils.OutputData(itemList)
	},
}
